package cn.csdj.sism.service.impl;

import cn.csdj.sism.dao.EmployeeMapper;
import cn.csdj.sism.dao.UserMapper;
import cn.csdj.sism.dao.UserRoleMapper;
import cn.csdj.sism.pojo.User;
import cn.csdj.sism.pojo.UserRole;
import cn.csdj.sism.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    public int update(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectList(null);
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public HashMap userLogin(User user){
        HashMap result = new HashMap();
        try {
            //通过userCode和password查询user
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper();
            lqw.eq(User::getUserCode,user.getUserCode()).eq(User::getPassword,user.getPassword());
            user = userMapper.selectOne(lqw);
            //通过user的empId查询员工姓名 存入返回信息中
            Integer empId = user.getEmpId();
            String empName = employeeMapper.selectById(empId).getEmpName();
            result.put("empName",empName);
            //通过userId查询对应的roleId 存入返回信息中
            Integer userId = user.getUserId();
            LambdaQueryWrapper<UserRole> lqw2 = new LambdaQueryWrapper();
            lqw2.eq(UserRole::getUserId,userId);
            UserRole userRole = userRoleMapper.selectOne(lqw2);
            Integer roleId = userRole.getRoleId();
            result.put("roleId",roleId);
            result.put("success",1);//1表示查询成功
        }catch (Exception e){
            e.printStackTrace();//打印异常信息
            result.put("success",0);//0表示查询失败
        }finally {
            return result;
        }
    }
}

